package main

import (
	"html/template"

	"time"

	DB "./databases"
	f "./logger"
	"github.com/gin-gonic/gin"
	"github.com/go-ego/gse"
)

func unescapeHTML(s string) template.HTML {
	return template.HTML(s)
}

//开启异步特性  要求3.6+
func main() {

	tStr := time.Now().Format("2006-01-02")
	newLog := f.NewFlieLogger("warnig", "logfile", tStr+".log", 100*1024*1024)

	r := gin.Default()
	r.LoadHTMLGlob("src/view/master/*") //解析模板
	// 启动静态文件服务,没有这个不显示css
	r.Static("/statics", "src/statics")

	r.GET("/", func(c *gin.Context) {
		//http请求
		c.HTML(200, "index.html", gin.H{ //模板渲染
			"title": "Spider",
		})
	})
	r.GET("/index", func(c *gin.Context) {
		//http请求
		c.HTML(200, "index.html", gin.H{ //模板渲染
			"title": "Spider",
		})
	})
	r.POST("./index", func(c *gin.Context) {
		//http请求
		c.HTML(200, "index.html", gin.H{ //模板渲染
			"title": "Spider",
		})
	})
	r.GET("/search", func(c *gin.Context) {
		query := c.Query("q")
		if query == "" {

			c.HTML(200, "index.html", gin.H{ //模板渲染
				"title": "Spider",
			})
		} else {
			var seg gse.Segmenter
			seg.LoadDict("zh_s")
			seg_query := seg.Cut(query)

			newLog.Debug(query)

			word_id_list := DB.MongoCliQuery_word_id(seg_query)

			index_cur := DB.MongoCliQuery_inverted_index(word_id_list)

			var doc_id_list []int
			for i := 0; i < len(index_cur); i++ {
				cur_doc_id := 0
				for j := 0; j < len(index_cur[i].Inverted_list); j++ {
					cur_doc_id += index_cur[i].Inverted_list[j][0]

					doc_id_list = append(doc_id_list, cur_doc_id)
				}
			}
			queryres := DB.MongoCliQuery_doc_id(doc_id_list)

			c.HTML(200, "search.html", gin.H{ //模板渲染
				"title": "Spider",
				"res":   queryres,
			})
		}
	})

	r.Run(":8080") //启动server
}
